<?php
class Location extends EMongoDocument {
	public $name = "";
	public $type_location = ""; // loai khu vuc: tinh_thanh, quan_huyen, phuong_xa
	public $root = ""; // parent location

	public static function model($className=__CLASS__){
		return parent::model($className);
	}

	// This method is required!
	public function getCollectionName(){
		return 'tbl_location';
	}

	public function rules(){
		$rules = array();
		$rules[] = array('name','required','message' => 'Vui lòng nhập tên địa điểm');
		return $rules;
	}

	public function attributeLabels(){
		return array(
			'name' => 'Tên địa điểm',
			'type_location' => 'Loại địa điểm',
			'root' => 'Địa điểm cha',
		);
	}


	public function search(){
		$cond = new EMongoCriteria;
		if(!empty($this->type_location)){
			$cond->type_location = $this->type_location;
		}else{
			$cond->root = "";
		}
		if(!empty($this->name)){
			$cond->name = new MongoRegex("/".$this->name."/i");
		}
		return new EMongoDocumentDataProvider('Location', array(
			'criteria' => $cond,
		    'sort'=>array(
		        'attributes'=>array(
					'name'		            
		        )
		    ),
		    'pagination' => array(

	    	)
		));
	}

	public function loadFullLocation(){
		$result = array();
		$result[] = "";
		$criP = new EMongoCriteria;
		$criP->root = "";
		$criP->sort("name",EMongoCriteria::SORT_DESC);
		$data = $this->findAll($criP);
		foreach($data as $l){
			$criC = new EMongoCriteria;
			$criC->root = $l['_id']."";
			$criC->sort("name",EMongoCriteria::SORT_DESC);
			$child = $this->findAll($criC);
			if(empty($child)){
				$result[$l['_id'].''] = $l['name'].'';
			}else{
				$childData = array();
				foreach($child as $cl){
					$childData[$cl['_id'].''] = $cl['name'];
				}
				$result[$l['name'].''] = $childData;
			}
		}
		return $result;
	}

	public function loadAllTinhThanh(){
		$result = array();
		$data = $this->findAllByAttributes(array("root"=>0));
		foreach($data as $d){
			$result[$d['_id'].''] = $d['name'];
 		}
		return $result;
	}

	public function listTypeLocation($k = null){
		$arr = array(
			"tinh_thanh" => "Tỉnh thành", 
			"quan_huyen" => "Quận huyện", 
			"phuong_xa"  => "Phường xã"
		);
		if(!is_null($k)){
			if(isset($arr[$k]))
				return $arr[$k];
			return "";
		}
		return $arr;
	}
}
?>